package com.ruoyi.systemapp.netty;

import com.ruoyi.systemapp.utils.Disroute;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import proto.client.ProtoCmd;

import javax.annotation.PostConstruct;
import java.util.stream.Collectors;

/**
 * Author:cgChen
 * Date:2022/05/14 15:31
 * Description:netty服务端处理器
 */
//@Service("NettyServerHandler")
@Configurable
@Component
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    private static Logger log = LoggerFactory.getLogger(NettyServerHandler.class);
    @Autowired
    private Disroute disroute;
    private static NettyServerHandler nettyServerHandler;
    @PostConstruct
    public void init() {
        nettyServerHandler=this;
        // 这里放要执行的赋值
    }
    /**
     * 客户端连接会触发
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("Channel active......");
        String remoteAddress = ctx.channel().remoteAddress().toString();
        System.out.println("有客户端连接... 客户端地址" + remoteAddress);
        NettyServer.remoteAddressMap.put(remoteAddress, ctx);
        super.channelActive(ctx);
        //channel=ctx.channel();
        //UserInfo.Login.Builder userMsg=UserInfo.Login.newBuilder();
        //userMsg.setPhone("123123123");
        //userMsg.setPassword("123");
        //ProtoCmd.RequestCmd.Builder cmd=ProtoCmd.RequestCmd.newBuilder();
        //cmd.setPact(0x01);
        //cmd.setCode(101);
        //cmd.setData(userMsg.build().toByteString());
        //ctx.write(cmd.build());
        //ctx.flush();
    }

    /**
     * 客户端发消息会触发
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("服务器收到消息: {}", msg);
        ProtoCmd.RequestCmd cmd= (ProtoCmd.RequestCmd) msg;
        if(cmd.getPact()!=0x01){
            return;
        }
        byte[] response = nettyServerHandler.disroute.onMessage(cmd.getData().toByteArray(),cmd.getCode());
        //回复消息
        ProtoCmd.ResponseCmd responseCmd=ProtoCmd.ResponseCmd.parseFrom(response);
        sendMsg(responseCmd,ctx);
        //ctx.channel().writeAndFlush(responseCmd);
    }

    //public void sendClient(){
    //    String key = NettyServer.remoteAddressMap.keySet().stream().collect(Collectors.toList()).get(0);
    //    if(key!=null){
    //        ProtoCmd.ResponseCmd.Builder responseCmd=ProtoCmd.ResponseCmd.newBuilder();
    //        responseCmd.setPact(0x01);
    //        responseCmd.setCode(101);
    //        responseCmd.setMsg("12312321");
    //        NettyServer.remoteAddressMap.get(key).writeAndFlush(responseCmd.build());
    //    }
    //}

    /**
     * 向客户端发送消息
     *
     * @param msg
     * @throws Exception
     */
    public void sendMsg(Object msg,ChannelHandlerContext ctx) throws Exception {
        String remoteAddress = ctx.channel().remoteAddress().toString();
        if (NettyServer.remoteAddressMap != null) {
            NettyServer.remoteAddressMap.get(remoteAddress).writeAndFlush(msg);
        } else {
            log.warn("消息发送失败,连接尚未建立!");
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        String remoteAddress = ctx.channel().remoteAddress().toString();
        System.out.println("有客户端断开连接... " + remoteAddress);
        NettyServer.remoteAddressMap.remove(remoteAddress);
        super.channelInactive(ctx);
    }

    /**
     * 发生异常触发
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

}
